import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/page/common/common_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/train/model/train_stream.dart';
import 'package:flutter_learn_vi/src/page/train/train_header_time_widget.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_start_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/16.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
/// 学员开始上课
/// 教师点击开始上课后 学员可以进行签到
class TrainStudentStartWidget extends StatefulWidget {
  final TrainApproveBean approveBean;

  const TrainStudentStartWidget({Key key, this.approveBean}) : super(key: key);

  @override
  _TrainTeacherStartWidgetState createState() =>
      _TrainTeacherStartWidgetState();
}

class _TrainTeacherStartWidgetState extends State<TrainStudentStartWidget>
    with TrainModel {
  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    _getStudentCourseIng();
    _streamSubscription = trainStream.stream.listen((TrainEventBean event) {
      if (event.statues == 2) {
        _getStudentCourseIng();
      }
    });
  }

  @override
  void dispose() {
    _streamSubscription.cancel();
    stopTimer();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(left: 12, right: 12, bottom: 6),
        width: double.infinity,
        constraints: BoxConstraints(minHeight: 240),
        child: Card(
          child: Padding(
            padding: EdgeInsets.all(8),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                startCourse(),
                Container(
                  padding: EdgeInsets.only(top: 10, bottom: 10),
                  child: buildHeader(),
                ),
              ],
            ),
          ),
        ));
  }

  Widget startCourse() {
    if (_isLoading) {
      return LoadingWidget();
    }

    Color color = Color(0xff37967f);

    if (_courseBean != null) {
      color = Color(0xff1b83c9);
    }
    return buildClipOval(color);
  }

  Widget buildClipOval(color) {
    if (_courseBean == null) {
      return NoDataWidget(
        text: "暂无正在培训的课程\n请等待教师开始上课",
        clickCallBack: () {
          _getStudentCourseIng();
        },
      );
    }

    if (_signBean != null && _signBean.statues == 1) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // TextButton(
          //   child: Text("评价本小节课程"),
          //   onPressed: () {},
          // ),
          Text("签到时间：${_signBean.createTime}"),
          Text("签退时间：${_signBean.signUpTime}"),
        ],
      );
    }

    return Container(
      margin: EdgeInsets.only(top: 22, bottom: 22),
      child: ClipOval(
        child: Material(
          color: color,
          child: InkWell(
            onTap: () {
              if (_courseBean != null) {
                if (_signBean == null) {
                  signRequest();
                } else {
                  signUpCheckFunction();
                }
              } else {
                NavigatorUtils.pushPage(
                    context,
                    TrainTeacherSelectCoursePage(
                      approveBean: widget.approveBean,
                    ), callback: (value) async {
                  if (value != null) {
                    //查询是否有正在开始的课程
                    await _getStudentCourseIng();
                    //数据状态
                    _courseBean.studyStatues = 0;
                    //发送消息刷新
                    trainStream.add(TrainEventBean(0, _courseBean));
                  }
                });
              }
            },
            child: Container(
              alignment: Alignment.center,
              width: 120,
              height: 120,
              child: Text(
                _signBean != null ? "签退" : "签到",
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                  fontSize: 20,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  buildHeader() {
    if (_courseBean == null) {
      return TrainHeaderTimerWidget();
    } else if (_courseBean.studyStatues == 1) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text("已结束课程:"),
              Expanded(
                  child: Text(
                      "${_courseBean.courseName}->${_courseBean.courseName}")),
            ],
          ),
          Row(
            children: [
              Text("上课时间:"),
              Expanded(child: Text("${_courseBean.startTime}")),
            ],
          ),
          Row(
            children: [
              Text("下课时间:"),
              Expanded(child: Text("${_courseBean.updateTime}")),
            ],
          ),
          SizedBox(
            height: 22,
          ),
          Row(
            children: [
              Text(
                "请在30分钟内容签退，否则会以漏卡处理",
                style: TextStyle(fontSize: 14, color: Colors.redAccent),
              )
            ],
          )
        ],
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
            height: 22,
            child: Row(
              children: [
                Container(width: 90, child: Text("当前时间")),
                SizedBox(
                  width: 8,
                ),
                TrainHeaderTimerWidget(),
              ],
            )),
        SizedBox(
          height: 4,
        ),
        Container(
            height: 22,
            child: Row(
              children: [
                Container(width: 90, child: Text("开始时间")),
                SizedBox(
                  width: 8,
                ),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      "assets/images/2.0x/time_icon.png",
                      width: 18,
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text("${_courseBean.startTime}"),
                  ],
                ),
              ],
            )),
        SizedBox(
          height: 4,
        ),
        Container(
            height: 22,
            child: Row(
              children: [
                Container(width: 90, child: Text("已上课程时间")),
                SizedBox(
                  width: 8,
                ),
                TrainHeaderTimerWidget(startTime: _courseBean.startTime),
              ],
            )),
        SizedBox(
          height: 4,
        ),
        Row(
          children: [
            Text("当前正在进行的课程"),
          ],
        ),
        Row(
          children: [
            Expanded(
                child: Text(
                    "${_courseBean.courseName}->${_courseBean.courseName}")),
          ],
        )
      ],
    );
  }

  bool _isLoading = true;
  CourseBean _courseBean;
  TrainCourseSignBean _signBean;

  //获取正在培训的课程
  Future<bool> _getStudentCourseIng() async {
    List<CourseBean> courseList =
        await getStudentCourseNetDatils(widget.approveBean.trainId);

    if (courseList != null && courseList.length > 0) {
      _courseBean = courseList[0];
    } else {
      _courseBean = null;
    }
    if (_courseBean != null) {
      _signBean = await getTrainCourseSignDatils(_courseBean.courseId,
          _courseBean.courseList[0].courseId, widget.approveBean.trainId);
    }
    _isLoading = false;
    if (_courseBean == null) {
      stopTimer();
      startTimer();
    } else {
      stopTimer();
    }
    if (mounted) {
      setState(() {});
    }
    return Future.value(true);
  }

  void signUpCheckFunction() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定签退吗??",
        selectCallBack: () {
          signUpRequest();
        });
  }

  ///签退
  void signUpRequest() async {
    setState(() {
      _isLoading = true;
    });
    // await trainCourseSignUp(_signBean.id, _courseBean.trainStartId);
    await _getStudentCourseIng();
    setState(() {
      _isLoading = false;
    });
  }

  ///签到
  void signRequest() async {
    setState(() {
      _isLoading = true;
    });
    // await trainCourseSign(_courseBean, widget.approveBean.trainId);
    await _getStudentCourseIng();
    setState(() {
      _isLoading = false;
    });
  }

  Timer _timer;

  void startTimer() {
    _timer = Timer.periodic(Duration(seconds: 2), (timer) {
      _getStudentCourseIng();
    });
  }

  void stopTimer() {
    if (_timer != null && _timer.isActive) {
      _timer.cancel();
      _timer = null;
    }
  }
}
